const path = require("path")
const config =require('./src/config.js')
//环境变量
const env = process.env.NODE_ENV === 'development'
module.exports = {
  runtimeCompiler: true,
  publicPath:'./', // 部署应用包时的基本 URL
  outputDir: 'dist', // 生产环境构建文件的目录
  assetsDir: 'static', // 放置生成的静态资源 (js、css、img、fonts) 的 (相对于 outputDir 的) 目录
  productionSourceMap: false, // 生产环境是否生成 sourceMap 文件
  transpileDependencies: true, // 允许两种编码引入方式共存,也就是 common 规范与 es6 规范的共存处理
  configureWebpack: {
    name: config.name,
    devtool:'source-map'
  },
  devServer: {
    open: false,
    host: '0.0.0.0', //使用转发工具
    allowedHosts: 'all',// 解决跨域问题
    port: 14002,  //端口
    client: {
      overlay: false
    },
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Headers": "*",
      "Access-Control-Allow-Methods": "*",
    },
  },

  // 通过 webpack-merge 合并到最终的配置中
  chainWebpack: (config) => {
    config.plugins.delete('prefetch').delete('preload') // 移除 prefetch 插件
    config.resolve.symlinks(true) // 修复热更新失效
    // 设置路径别名
    config.resolve.alias.set('@', path.resolve(__dirname, './src'))
    // 配置 svg-sprite-loader
    const imagesRule = config.module.rule('images')
    imagesRule.test(/\.(png|jpe?g|gif|webp|svg)(\?.*)?$/).exclude.add(require('path').resolve(__dirname, 'src/assets/icons')).end()
    //开发环境 sourcemap 不包含列信息
    config.when(!env, config => {config.devtool('cheap-source-map')})
    // //添加一个时间戳htmlWebpackPlugin.options.version
    config.plugin('html').tap((args) => {
      args[0].version = new Date().getTime()
      return args})
    //script脚本切分
    config.optimization.splitChunks({
      chunks: 'all',
      cacheGroups: {
        commons: {
          name: 'chunk-commons',
          test: path.resolve('src/components'),
          minChunks: 3,
          priority: 5,
          reuseExistingChunk: true, // 公共模块必开启
          enforce: true,
        },
        libs: {
          name: 'chunk-libs',
          test: /[\\/]node_modules[\\/]/,
          priority: 10,
          chunks: 'initial',
        },
        elementUI: {
          name: 'chunk-elementUI',
          priority: 20,
          test: /[\\/]node_modules[\\/]_?element-ui(.*)/,
        },
        lodash: {
          name: 'chunk-lodash',
          priority: 20,
          test: /[\\/]node_modules[\\/]_?lodash(.*)/,
        },
      },
    })
    //将运行时代码提取到单独的块中以实现更好的缓存。
    config.optimization.runtimeChunk('single')

  }
}
